<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="###Android WebView与JavaScript代码交互  首先先准备一段网页代码123456789String DATA = &amp;quot;&amp;lt;p&amp;gt;    为加快推进2017年度自治区水土保持重点工程前期工作，按照水利厅《关于做好2017年度水土保持重点工程项目前期工作的通知》要求，2017年4月27日，水利厅水保处一行三人在赵宏新副处长的带领下。对昌吉州2017年度水土保持重">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="Android-WebView与JavaScript代码交互">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/Android/Android-WebView与JavaScript代码交互/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="###Android WebView与JavaScript代码交互  首先先准备一段网页代码123456789String DATA = &amp;quot;&amp;lt;p&amp;gt;    为加快推进2017年度自治区水土保持重点工程前期工作，按照水利厅《关于做好2017年度水土保持重点工程项目前期工作的通知》要求，2017年4月27日，水利厅水保处一行三人在赵宏新副处长的带领下。对昌吉州2017年度水土保持重">
<meta property="og:locale" content="default">
<meta property="og:updated_time" content="2018-08-06T11:22:10.571Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android-WebView与JavaScript代码交互">
<meta name="twitter:description" content="###Android WebView与JavaScript代码交互  首先先准备一段网页代码123456789String DATA = &amp;quot;&amp;lt;p&amp;gt;    为加快推进2017年度自治区水土保持重点工程前期工作，按照水利厅《关于做好2017年度水土保持重点工程项目前期工作的通知》要求，2017年4月27日，水利厅水保处一行三人在赵宏新副处长的带领下。对昌吉州2017年度水土保持重">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/Android/Android-WebView与JavaScript代码交互/"/>





  <title>Android-WebView与JavaScript代码交互 | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/Android/Android-WebView与JavaScript代码交互/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android-WebView与JavaScript代码交互</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>###Android WebView与JavaScript代码交互</p>
<ol>
<li>首先先准备一段网页代码<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">String DATA = &quot;&lt;p&gt;    为加快推进2017年度自治区水土保持重点工程前期工作，按照水利厅《关于做好2017年度水土保持重点工程项目前期工作的通知》要求，2017年4月27日，水利厅水保处一行三人在赵宏新副处长的带领下。对昌吉州2017年度水土保持重点工程前期工作开展情况进行了监督检查。 &lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;    首先，检查组一行对玛纳斯县旱卡子滩哈萨克乡闽玛生态村进行了实地调研，该村是全疆第一个以“绿色、生态、宜居”为设计理念而高标准建设的牧民定居工程，工程建设与当地自然景观相协调，基本实现人与自然的和谐共处，经济社会的可持续发展，生态环境的良性循环。“十二五”期间，水利厅在该区域已安排了两期水土保持综合治理工程建设，治理水土流失面积14平方公里，蓄水保土效益、生态效益和社会效益显著。 &lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;    随后，检查组对拟选定列入2017年水土保持重点工程建设计划中的玛纳斯县沙河小流域水土保持综合治理工程项目区进行了现场查看，详细了解了项目实施方案的编报、审查和审批工作情况，及项目区选址、建设规模及投资等情况，实施方案编制单位项目负责人员在现场详细介绍了工程实施方案的设计情况，听取了昌吉州水利局和玛纳斯县水利局有关负责同志对实施方案设计总体思路、治理措施布设、及如何将水土保持重点治理项目与闽玛生态村周边生态建设工程项结合的介绍后，检查组认为，玛纳斯县沙河小流域水土保持综合治理工程项目区选址合理可行，与前两期已实施的项目结合并集中连片实施，符合水土保持综合治理的要求。 &lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;    现场检查后，检查组一行与昌吉州水利局、玛纳斯县水利局的有关领导及项目实施方案设计单位的设计人员进行了座谈，在结合了闽玛生态村规划和建设的经验后一致认为：水土保持综合治理工程是社会经济发展的要求，是落实习近平总书记系列讲话中“宁要绿水青山，不要金山银山”重要思想的重要举措，前期工作尤为重要，一是要按照“统一规划、分步实施、稳步推进”的原则和构建“生态修复、生态治理、生态保护”三道水土保持防线的思路进行建设；二是要将人与自然和谐相处的理念、以人为本的理念、可持续发展的理念以及保护自然生态等新理念贯穿进水土保持综合治理工程中，使水土保持工作突出生态优先，治理措施与自然景观相协调；三是要加大水土保持宣传力度，让水土保持走进千家万户、走进学校课堂，让越来越多的人了解水土保持工作，逐渐增强水土生态保护意识；四是要在管理上层层落实责任主体，严格按照水土保持重点工程建设管理程序要求做好洋沙小流域水土保持综合治理工程建设，同时，要加强与相关部门的配合和沟通，使各方面的资金捆绑使用，突显规模效益。&lt;/p&gt;\n&quot;</span><br><span class="line">    + &quot;&lt;p&gt; &lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;&lt;img style=\&quot;WIDTH: 263px; HEIGHT: 156px\&quot; border=\&quot;0\&quot; width=\&quot;675\&quot; height=\&quot;472\&quot; src=\&quot;http://www.xjslt.gov.cn/static/ewebeditor/uploadfile/img3/20170505130428623001.jpg\&quot;&gt;   &lt;img style=\&quot;WIDTH: 256px; HEIGHT: 159px\&quot; border=\&quot;0\&quot; width=\&quot;775\&quot; height=\&quot;745\&quot; src=\&quot;http://www.xjslt.gov.cn/static/ewebeditor/uploadfile/img3/20170505130451341001.jpg\&quot;&gt;  &lt;img style=\&quot;WIDTH: 216px; HEIGHT: 158px\&quot; border=\&quot;0\&quot; width=\&quot;711\&quot; height=\&quot;676\&quot; src=\&quot;http://www.xjslt.gov.cn/static/ewebeditor/uploadfile/img3/20170505130538948001.jpg\&quot;&gt;&lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;&lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;&lt;br&gt;\n&quot;</span><br><span class="line">    + &quot;&lt;/p&gt;&quot;;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<a id="more"></a>
<ol start="2">
<li>创建工程，并在布局文件设置WebView以及在显示的Activity完成findViewById()操作。<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;</span><br><span class="line">&lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;</span><br><span class="line">    xmlns:tools=&quot;http://schemas.android.com/tools&quot;</span><br><span class="line">    android:id=&quot;@+id/activity_main&quot;</span><br><span class="line">    android:layout_width=&quot;match_parent&quot;</span><br><span class="line">    android:layout_height=&quot;match_parent&quot;</span><br><span class="line">    tools:context=&quot;com.mazaiting.webviewtest.MainActivity&quot;</span><br><span class="line">    &gt;</span><br><span class="line"></span><br><span class="line">  &lt;WebView</span><br><span class="line">      android:id=&quot;@+id/webView&quot;</span><br><span class="line">      android:layout_width=&quot;wrap_content&quot;</span><br><span class="line">      android:layout_height=&quot;wrap_content&quot;</span><br><span class="line">      /&gt;</span><br><span class="line">&lt;/RelativeLayout&gt;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">@Override protected void onCreate(Bundle savedInstanceState) &#123;</span><br><span class="line">  super.onCreate(savedInstanceState);</span><br><span class="line">  setContentView(R.layout.activity_main);</span><br><span class="line"></span><br><span class="line">  WebView webView = (WebView) findViewById(R.id.webView);</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="3">
<li><p>加载网页,执行这段代码时，要添加网络权限，因为数据中含有网络图片。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">webView.loadData(DATA,&quot;text/html;charset=UTF-8&quot;, &quot;UTF-8&quot;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>设置WebView与JavaScript交互,创建一个类，类中创建一个方法，并添加@JavascriptInterface注解。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">public class JavaScriptInterface&#123;</span><br><span class="line">  @JavascriptInterface</span><br><span class="line">  public void openImage(String path)&#123; // 获取到图片链接，函数内执行自己的想要执行的逻辑</span><br><span class="line">    Toast.makeText(MainActivity.this, path, Toast.LENGTH_SHORT).show();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>WebView图片点击代码配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">final WebView webView = (WebView) findViewById(R.id.webView);</span><br><span class="line">/**</span><br><span class="line"> * 处理将Html中的网页图片点击</span><br><span class="line"> */</span><br><span class="line">// 1. 获取WebView的设置对象</span><br><span class="line">WebSettings settings = webView.getSettings();</span><br><span class="line">settings.setJavaScriptEnabled(true);</span><br><span class="line">// 3. 设置允许JavaScript弹窗</span><br><span class="line">settings.setJavaScriptCanOpenWindowsAutomatically(true);</span><br><span class="line">// 4. 防止中文乱码</span><br><span class="line">settings.setDefaultTextEncodingName(&quot;UTF-8&quot;);</span><br><span class="line">// 5. 加载网页</span><br><span class="line">webView.loadData(DATA,&quot;text/html;charset=UTF-8&quot;, &quot;UTF-8&quot;);</span><br><span class="line">// 6. 载入JavaScript</span><br><span class="line">webView.addJavascriptInterface(new JavaScriptInterface(), &quot;imageListener&quot;);</span><br><span class="line">// 7. 设置WebView客户端</span><br><span class="line">webView.setWebViewClient(new WebViewClient()&#123;</span><br><span class="line">  /**页面加载完成*/</span><br><span class="line">  @Override public void onPageFinished(WebView view, String url) &#123;</span><br><span class="line">    super.onPageFinished(view, url);</span><br><span class="line">    // 这段JavaScript函数的功能就是注册监听，遍历所有的img标签，并添加</span><br><span class="line">    // onClick函数，函数的功能是在图片点击的时候调用本地Java接口并传递url过去</span><br><span class="line">    webView.loadUrl(&quot;javascript:(function()&#123;&quot; +</span><br><span class="line">        &quot;var obj = document.getElementsByTagName(\&quot;img\&quot;);&quot; +</span><br><span class="line">        &quot;for(var i=0;i&lt;obj.length;i++)&#123;&quot; +</span><br><span class="line">        &quot;obj[i].onclick=function()&#123;&quot; +</span><br><span class="line">        &quot;window.imageListener.openImage(this.src)&#125;&quot; +</span><br><span class="line">        &quot;&#125;&quot; +</span><br><span class="line">        &quot;&#125;)()&quot;);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
</ol>
<p><a href="http://git.oschina.net/zaitingma/codes/lkh1pw29xy03o7je6z5cv10" target="_blank" rel="noopener">代码下载</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/Android/Android-SwipeRefreshLayout下拉刷新/" rel="next" title="Android-SwipeRefreshLayout下拉刷新">
                <i class="fa fa-chevron-left"></i> Android-SwipeRefreshLayout下拉刷新
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/Android/Android-命令行获取apk信息/" rel="prev" title="Android-命令行获取apk信息">
                Android-命令行获取apk信息 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
